package com.bzsg.simpleMediaPlayer.learn

import android.content.ContentUris
import android.content.Context
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bzsg.simpleMediaPlayer.R
import com.bzsg.simpleMediaPlayer.jni.NativeCodecHandler
import com.bzsg.simpleMediaPlayer.ui.pager.MainScreen
import com.bzsg.simpleMediaPlayer.ui.theme.SimpleMediaPlayerTheme
import com.bzsg.simpleMediaPlayer.viewModel.VideoStateViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class StudyActivity : ComponentActivity() {
    //    val codec =NativeCodecHandler.NativeImpl()
    private val viewModel: VideoStateViewModel by viewModels()

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.orientationEvent.collect { orientation ->
                    requestedOrientation = orientation
                }
            }
        }
        enableEdgeToEdge()
        setContent {
//            // 确保已获取媒体列表
//            val drawerState = rememberDrawerState(DrawerValue.Closed)
//            val scope = rememberCoroutineScope()
//
//            data class Item(val name: String, val icon: Int)
//            var selectedItem by remember { mutableStateOf(0) }
//            val items = listOf(
//                Item("主页", R.drawable.test),
//                Item("列表", R.drawable.test),
//                Item("设置", R.drawable.test)
//            )
//            SimpleMediaPlayerTheme(dynamicColor = false) {
//                ModalNavigationDrawer(
//                    drawerState = drawerState,
//                    drawerContent = {
//                        // 1. 添加Material3标准内边距
//                        Column(Modifier.padding(16.dp)) {
//
//                            // 2. 符合规范的文本展示
//                            NavigationDrawerItem(
//                                label = {
//                                    Text("text", style = MaterialTheme.typography.titleMedium)
//                                },
//                                icon = {
//                                    Icon(
//                                        Icons.Filled.Info,
//                                        contentDescription = "信息图标",
//                                        tint = MaterialTheme.colorScheme.primary
//                                    )
//                                },
//                                // 3. 添加波纹反馈
//                                onClick = { /* 点击操作 */ },
//                                // 4. 应用Material3动态色彩
//                                colors = NavigationDrawerItemDefaults.colors(
//                                    unselectedContainerColor = Color.Transparent
//                                ),
//                                selected = false
//                            )
//
//                            // 5. 添加分隔线（Material3规范要求）
//                            Divider(
//                                modifier = Modifier.padding(vertical = 8.dp),
//                                color = MaterialTheme.colorScheme.outlineVariant
//                            )
//                        }
//                    },
//                ) {
//                    Scaffold(
//                        modifier = Modifier.fillMaxSize(),
//                        topBar = {
//                            TopAppBar(title = { Text("播放器") }, navigationIcon = {
//                                IconButton(onClick = {}) {
//                                    Icon(Icons.Filled.Menu, null)
//                                }
//                            })
//                        },
//
//                        bottomBar = {
//                            NavigationBar {
//                                items.forEachIndexed { index, item ->
//                                    NavigationBarItem(
//                                        selected = selectedItem == index,
//                                        onClick = { selectedItem = index },
//                                        icon = {
//                                            Icon(painterResource(item.icon), null)
//                                        },
//                                        label = { Text(item.name) })
//                                }
//
//                            }
//                        }
//                    ) { innerPadding ->           // 边衬物的padding(竖屏上(状态栏)下（导航栏）左右)
//                        Box(modifier = Modifier
//                            .padding(innerPadding)
//                            .fillMaxSize()) {
//                            VideoGalleryScreen()
//                        }
//
//                      //  demo2(scaffoldModifier = Modifier.padding(innerPadding))
//                     // NewGreeting(scaffoldModifier = Modifier.padding(PaddingValues(top = innerPadding.calculateTopPadding())),codec)
//                    }
//                }
//            }
            SimpleMediaPlayerTheme(dynamicColor = false) {
                MainScreen()
            }
        }

//        codec.setCallback(object : NativeCodecCallback {
//            override fun onPrepared() {
//                Log.i("fhq", "onPrepared: ")
//                requestVideoPermission(context = this@StudyActivity)
//               // val pfd = context.contentResolver.openFileDescriptor(videoUri, "r")
//              // codec.start(pfd?.fd?:0)
//            }
//
//            override fun onError() {
//            }
//        })
    }

//    private val REQUEST_CODE = 101
//
//    private fun requestVideoPermission(context: Context) {
//        val permissions =
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                arrayOf(Manifest.permission.READ_MEDIA_VIDEO)
//            } else {
//                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
//            }
//
//        if (permissions.any { ContextCompat.checkSelfPermission(context, it) != PERMISSION_GRANTED }) {
//            ActivityCompat.requestPermissions(context as Activity, permissions, REQUEST_CODE)
//        } else {
//            // scanByMediaStore(context)
//        }
//    }
}

// 2.1Modifier修饰符
@Composable
fun NewGreeting(
    scaffoldModifier: Modifier = Modifier,
    codec: NativeCodecHandler.NativeImpl,
) {
    // 2.1.1常用修饰符
    // 1. Modifier.size(width = 100.dp, height = 100.dp)
    Column {
        Image(
            painterResource(id = R.drawable.ic_launcher_background),
            contentDescription = "hello_world",
            modifier =
                scaffoldModifier
                    .size(60.dp)
                    .clip(CircleShape),
        )
        Spacer(Modifier.width(10.dp))
        // contentDescription 参数的核心作用是 为图像提供语义化描述，以支持无障碍功能（如屏幕阅读器）
        Image(
            painterResource(id = R.drawable.ic_launcher_background),
            contentDescription = "hello_world",
            modifier =
                Modifier
                    .size(width = 100.dp, height = 100.dp)
                    .clip(CircleShape),
        )
        // 2.Modifier.background
        Box(
            Modifier
                .size(50.dp)
                .background(color = Color.Red),
        ) {
            Text("helloWorld()", Modifier.align(Alignment.Center))
        }
        Spacer(Modifier.width(10.dp))
        Box(
            Modifier
                .size(50.dp)
                .background(
                    brush =
                        Brush.verticalGradient(
                            colors =
                                listOf(
                                    Color.Red,
                                    Color.Yellow,
                                    Color.White,
                                ),
                        ),
                ),
        ) {
            Text("渐变色", Modifier.align(Alignment.Center))
        }
        // 3.Modifier.fillMaxSize()填满整个父空间
        // Box(modifier = Modifier.fillMaxSize().background(Color.Red))
        Box(
            Modifier
                .fillMaxWidth()
                .height(60.dp)
                .background(Color.Red),
        )
        // 4. Modifier.border & Modifier.padding
        // 第一个.padding外边距
        // 第二个.padding内边距
        Box(
            Modifier
                .padding(8.dp)
                .border(2.dp, Color.Blue, shape = RoundedCornerShape(2.dp))
                .padding(8.dp),
        ) {
            Spacer(
                Modifier
                    .size(width = 100.dp, height = 100.dp)
                    .background(Color.Black),
            )
        }
        // 5. Modifier.offset
        Box(
            Modifier
                .fillMaxWidth()
                .height(300.dp),
        ) {
            NativeSurfaceProvider(codec)
        }
    }
}

// 必须包含 ID 才能构建 Uri
fun scanByMediaStore(context: Context) {
    val collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
    val projection =
        arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.RELATIVE_PATH,
            MediaStore.Video.Media.DATE_MODIFIED,
        )

    context.contentResolver.query(
        collection,
        projection,
        // 过滤空文件
        "${MediaStore.Video.Media.SIZE} > 0",
        null,
        "${MediaStore.Video.Media.DATE_MODIFIED} DESC",
    )?.use { cursor ->
        val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)

        while (cursor.moveToNext()) {
            val id = cursor.getLong(idColumn)
            val videoUri = ContentUris.withAppendedId(collection, id)
            // 获取其他信息（可选）
            val name =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME))
            val path =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.RELATIVE_PATH))
            Log.i("MediaStore", "URI: $videoUri | Path: $path/$name")
            // 使用示例：通过 Uri 打开文件
            // 通过 ContentResolver 获取 ParcelFileDescriptor
            val pfd = context.contentResolver.openFileDescriptor(videoUri, "r")
        }
    }
}

@Composable
fun NativeSurfaceProvider(codec: NativeCodecHandler.NativeImpl) {
    var surfaceHolder: SurfaceHolder? by remember { mutableStateOf(null) }
    AndroidView(
        factory = { ctx ->
            SurfaceView(ctx).apply {
                holder.addCallback(
                    object : SurfaceHolder.Callback {
                        override fun surfaceCreated(holder: SurfaceHolder) {
                            surfaceHolder = holder
                            codec.prepare(holder.surface, ctx.assets)
                        }

                        override fun surfaceChanged(
                            holder: SurfaceHolder,
                            format: Int,
                            width: Int,
                            height: Int,
                        ) {
                        }

                        override fun surfaceDestroyed(holder: SurfaceHolder) {
                        }
                    },
                )
            }
        },
        modifier = Modifier.fillMaxSize(),
    )
}

@Preview(showBackground = true)
@Composable
private fun NewGreetingPreview() {
}
